import { Layout, Button, Space, Table, message, Descriptions, Modal, Input } from 'myselfantd';
import React, { useState, useEffect, useMemo } from 'react';
import type { ColumnsType, TableProps } from 'antd/es/table';
import styles from './index.module.scss';
import { getList, updateMAttr } from '../api';
interface DataType {
  code: number;
  work: string;
  operateArea: number;
  operateDistance: number;
  taskEndTime: string;
  taskStatus: number;
  evaluationState: number;
  option: [];
}
interface Props {
  viewmode?: 'view' | 'add' | 'edit';
  data?: any;
  title?: string;
  id?: string;
  onFinish?: Function;
}
const App: React.FC<Props> = (props) => {
  const { viewmode, data = [], onFinish } = props;
  const [units, setUnits] = useState<any>([]);
  useEffect(() => {
    getList({}).then(({ result }: any) => {
      setUnits(result);
    });
  }, []);
  const [fields, setFields] = useState([] as any);
  useEffect(() => {
    if (data) {
      setFields(
        data.map((item: any, index: number) => ({
          ...item,
          sortkey: index + 1,
          ...JSON.parse(item.defaultValueJson || item.valueJson || "{}"),
        })),
      );
    }
  }, [data]);
  return (
    <>
      <Table.Form
        scroll={{ scrollToFirstRowOnChange: true, y: 350 }}
        pagination={{
          locale: {
            items_per_page: '条/页',
            jump_to: '跳至',
            page: '页',
          },
          showTotal: (total: any) => `共 ${total} 条数据`,
        }}
        value={fields}
        columns={useMemo(
          () => [
            {
              title: '序号',
              width: 150,
              fixed: 'left',
              align: 'left',
              render: (text: any, record: any, index: any) => {
                return index + 1;
              },
            },
            {
              title: '属性名称',
              width: 150,
              fixed: 'left',
              align: 'left',
              dataIndex: 'attributeName',
            },
            {
              title: '标识符',
              width: 150,
              textWrap: 'word-break',
              align: 'left',
              dataIndex: 'attributeCode',
            },
            {
              title: '数据类型',
              width: 150,
              textWrap: 'word-break',
              align: 'left',
              dataIndex: 'type',
              render: (_) => {
                enum TYPE {
                  数字类型 = 1,
                  字符串类型 = 2,
                  布尔类型 = 3,
                  枚举类型 = 4,
                }
                return TYPE[_];
              },
            },
            {
              title: '数据定义',
              width: 200,
              textWrap: 'word-break',
              ellipsis: true,
              align: 'left',
              dataIndex: 'defaultValueJson',
              render: (_: any, record: any) => {
                let dom: any = '';
                switch (record.type) {
                  case 1:
                    dom = (
                      <span>
                        <p>
                          <span>定义取值范围：</span>
                          {record.min} ~ {record.max}
                        </p>
                        <p>
                          <span>步长：</span>
                          {record.walkLength}
                        </p>
                        <p>
                          <span>单位：</span>
                          {units.find((item: any) => item.id === String(record.unitId))?.name}
                        </p>
                      </span>
                    );
                    break;
                  case 2:
                    dom = (
                      <span>
                        <span>数据长度：</span>
                        {record.stringResult}
                      </span>
                    );
                    break;
                  case 3:
                    dom = (
                      <span>
                        <span>布尔值：</span>
                        <Table.Edit
                          deleteButton={false}
                          value={record.booleanEnums.map((item: any, index: any) => ({
                            sortkey: index,
                            ...item,
                          }))}
                          pagination={false}
                          columns={[
                            {
                              title: '参数值',
                              dataIndex: 'enumKey',
                              showSorterTooltip: false,
                              width: 180,
                              onCell: (record: any) => {
                                return {
                                  filed: 'enumKey',
                                  record,
                                };
                              },
                            },
                            {
                              title: '参数描述',
                              dataIndex: 'enumDesc',
                              showSorterTooltip: false,
                              onCell: (record: any) => ({
                                filed: 'enumDesc',
                                record,
                              }),
                            },
                          ]}
                        />
                      </span>
                    );
                    break;
                  case 4:
                    dom = (
                      <span>
                        <span>枚举值：</span>
                        <Table.Edit
                          deleteButton={false}
                          value={record.enums.map((item: any, index: any) => ({
                            sortkey: index,
                            ...item,
                          }))}
                          pagination={false}
                          columns={[
                            {
                              title: '参数值',
                              dataIndex: 'enumKey',
                              showSorterTooltip: false,
                              width: 180,
                              onCell: (record: any) => {
                                return {
                                  filed: 'enumKey',
                                  record,
                                };
                              },
                            },
                            {
                              title: '参数描述',
                              dataIndex: 'enumDesc',
                              showSorterTooltip: false,
                              onCell: (record: any) => ({
                                filed: 'enumDesc',
                                record,
                              }),
                            },
                          ]}
                        />
                      </span>
                    );
                    break;
                }
                return dom;
              },
            },
            {
              title: '读写类型',
              width: 120,
              textWrap: 'word-break',
              ellipsis: true,
              align: 'left',
              dataIndex: 'readWriteType',
              render: (_: any, record: any) => {
                enum TYPE {
                  读 = 1,
                  读写 = 2,
                }
                return TYPE[record?.readWriteType];
              },
            },
            {
              title: '默认值',
              width: 120,
              textWrap: 'word-break',
              ellipsis: true,
              align: 'left',
              dataIndex: 'attributeValue',
              onCell: (record: any) => ({
                editable: true,
                filed: 'attributeValue',
                record,
                rules: [
                  {
                    required: true,
                    message: `默认值必填`,
                  },
                ],
                render: () => <Input placeholder="请填写默认值" />,
              }),
            },
          ],
          [units],
        )}
        onChange={async (data: any) => {
          setFields(data);
        }}
        singleOnChnage={async (data: any) => {
          let parmas = {
            deviceSkuId: props.id,
            id: data.id,
            value: data.attributeValue,
          };
          let res = await updateMAttr(parmas);
          if (res) {
            onFinish?.();
            message.success('数据更新成功');
          }
        }}
      />
    </>
  );
};

export default App;
